<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>

<video id="video" autoplay></video>
<button id="snap">拍照</button>
<canvas id="canvas"></canvas>
<script>
    document.addEventListener('DOMContentLoaded', (event) => {
        const video = document.getElementById('video');
        const canvas = document.getElementById('canvas');
        const snap = document.getElementById('snap');

        let stream;

        function startCamera() {
            if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
                navigator.mediaDevices.getUserMedia({ video: true })
                    .then(function (mediaStream) {
                        stream = mediaStream;
                        video.srcObject = mediaStream;
                        video.play();
                    })
                    .catch(function (error) {
                        console.error("Something went wrong!", error);
                    });
            }
        }

        function capture() {
            let context = canvas.getContext('2d');

            if (width && height) {
                canvas.width = width;
                canvas.height = height;
                context.drawImage(video, 0, 0, width, height);

                // 这里你可以将canvas转换为图片，比如使用toDataURL()方法
                // let dataUrl = canvas.toDataURL('image/png');
                // 然后你可以将dataUrl发送到服务器，或者做其他处理

                // 示例：在控制台中显示图片URL
                console.log(canvas.toDataURL('image/png'));
                const dataUrl = canvas.toDataURL('image/png');

            } else {
                console.log('Error: Could not access video stream (video.videoWidth is zero).');
            }
        }

        snap.addEventListener('click', () => {
            capture();
        });

        // 当页面加载时启动摄像头
        startCamera();

        // 这里可以监听窗口大小变化，以便调整canvas的大小以匹配视频
        window.addEventListener('resize', () => {
            if (video.videoWidth > 0 && video.videoHeight > 0) {
                // 设置video的宽度为窗口宽度的90%
                video.width = window.innerWidth * 0.9;
                // 保持视频宽高比
                video.height = (video.videoHeight / video.videoWidth) * video.width;
                // 更新宽度和高度变量（这里只是一个示例，你可能需要将这些值存储在某个地方）
                width = video.videoWidth;
                height = video.videoHeight;
            }
        });
    });
</script>
</body>
</html>